package cn.zhqr.core.utils;

import com.jfinal.plugin.redis.Redis;

/**
 * 库存锁
 */
public class StockLock {
    public static final int EXPIRE_SECOND = 60 * 10;
    public enum Stock{
        WASH_CARD
    }

    /**
     * 锁库存
     * @param stock     库存品类
     * @param num       锁库存的数量
     * @param time      锁定时间
     * @return
     */
    public static boolean lock(Stock stock,int num, int time){
        Long result = Redis.use().incrBy(stock.name(), num);
        Redis.use().expire(stock.name(), time);
        return result!=null;
    }

    /**
     * 获取库存锁数量
     * @param stock      库存品类
     * @return
     */
    public static Long getLockNum(Stock stock){
        try{
            Object result = Redis.use().get(stock.name());
            if(result==null) return 0L;
            return Long.parseLong(result.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0L;
    }

    /**
     * 释放库存
     * @param stock       库存品类
     * @param num         释放的库存数量
     * @return
     */
    public static boolean unlock(Stock stock,int num){
        Long result = Redis.use().decrBy(stock.name(),num);
        return result!=null;
    }
}
